import { Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { StatusFollowService } from '@core/statusFollow.service';
import { LocalStorage } from '@core/local.storage';
import { ReuseTabService } from '@delon/abc';
import { forkJoin } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'app-sxdaqkk.component',
  templateUrl: './sxdaqkk.component.html',
  styleUrls: ['./sxdaqkk.component.less']
})

export class SxdaqkkComponent implements OnInit {
  queryParam: any = {};
  tableData = []
  pageType: any;
  pageSize = '20';
  pageTotal = 0;
  pageIndex = 1;
  isMainPage = true;
  statusList = ['未盯控', '正在盯控', '已经完成'];
  detailParams: any;
  cjId: any;
  needSaveIndexes: any = new Set();
  lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
  isTicking = false;
  timeleft = 30;
  loading = false;

  constructor(
    private http: _HttpClient,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    public statusFollowService: StatusFollowService,
    private reuseTabService: ReuseTabService,
    public message: NzMessageService,
    private ls: LocalStorage,
  ) { }

  ngOnInit(): void {
    this.activatedRoute.params.subscribe(params => {
      this.pageType = params.pageType;
      if (params.id) {
        this.cjId = params.id;
      }
      const historyMenu = JSON.parse(this.ls.localStorage.historyMenu);
      const menuText = historyMenu[0].text;
      this.reuseTabService.title = (menuText || '') + '作业卡控';
      this.query(true);
    });
  }

  initDate() {
    const _date = new Date();
    this.queryParam.startdate = _date;
    this.queryParam.enddate = _date;
  }

  query(fromBeginning = false) {

    const param: any = {
      page: fromBeginning === false ? this.pageIndex : 1,
      limit: this.pageSize,
      uStatus: '',
    };
    if (this.queryParam._startdate) {
      param.startdate = this.datePipe.transform(this.queryParam._startdate, 'yyyy-MM-dd');
    }
    if (this.queryParam._enddate) {
      param.enddate = this.datePipe.transform(this.queryParam._enddate, 'yyyy-MM-dd');
    }

    let queryOb;
    switch (this.pageType) {
      case 'cj':
      case 'gtcj':
        param.uWorkshop = this.cjId;
        queryOb = this.query_cj(param)
        break;
      case 'hz':
        queryOb = this.query_hz(param);
        break;
    }
    queryOb.subscribe(res => {
      this.loading = false;
      this.tableData = res.data;
      this.pageTotal = res.count;
    });
  }


  statusFollow(data) {
    return this.statusFollowService.init('sxdaqkk', data);
  }

  noLeaving() {
    return this.isTicking || this.loading
  }

  /**
   * 删除私立字段
   * @param param 
   */
  removePrivateFields(param) {
    Object.keys(param).forEach(key => {
      if (!(key.indexOf('_'))) {
        delete param[key];
      }
    });
  }

  formatDate(param) {
    if (param._begindate) {
      param.begindate = this.datePipe.transform(param._begindate, 'yyyy-MM-dd');
    }
    if (param._enddate) {
      param.enddate = this.datePipe.transform(param._enddate, 'yyyy-MM-dd');
    }
  }


  /**
   * 车间表查询
   * @param page  string 页码
   * @param limit  string 每页显示数量
   * @param uWorkshop  string 车间编号
   * @param startdate  string 筛选-开始日期yyyy-MM-dd
   * @param enddate  string 筛选-截止日期yyyy-MM-dd
   * @param uStatus  string 筛选-0未盯控、1正在盯控、2已经完成
   */
  query_cj(param) {
    const dataurl = environment.project + '/updownRoadm/query';
    return this.http.get(dataurl, param);
  }
  /**
   * 报警类型统计
   * @param param begindate
   * @param param enddate
   */
  query_hz(param) {
    const dataurl = environment.project + '/updownRoadm/querySummary';
    return this.http.get(dataurl, param);
  }


  goDetail(row) {
    if (this.noLeaving()) {
      return;
    }
    this.isMainPage = false;
    const p = {
      // tabIndex: 0,
      uStatus: '',
      uWorkarea: '',
      uStation: '',
    };
    const _p: any = {};
    _p.showTab2 = true;
    switch (this.pageType) {
      case 'hz':
        _p.uSummary = '1';
        _p.uDate = row.uDate;
        // _p.nWorkshop = row.uWorkshop;       
        break;
      case 'cj':
        _p.uSummary = '0';
        // _p.uId = '397387037696856065';
        _p.uId = row.id;
        _p._cjId = this.cjId;
        break;
      case 'gtcj':
        _p.uSummary = '0';
        _p.uId = row.id;
        _p._cjId = this.cjId;
        break;
    }
    Object.assign(p, _p);
    this.detailParams = p;
  }

  goMain() {
    this.isMainPage = true;
    this.query();
  }

  onChange(v, index) {
    if (this.queryParam.uSummary === '1') {
      return;
    }
    this.needSaveIndexes.add(index);
    if (this.isTicking === false) {
      this.timeTick(true);
    } else {
      this.timeleft = 301;
    }
  }

  timeTick(reset?) {
    if (reset === true) {
      this.timeleft = 300;
    }
    if (this.timeleft === 0) {
      this.saveAll();
      this.isTicking = false;
      return;
    }

    setTimeout(() => {
      this.timeleft--;
      this.timeTick();
    }, 1000);
    this.isTicking = true;
  }

  saveAll() {
    const arr = Array.from(this.needSaveIndexes);
    const obs = [];
    arr.forEach((index: any) => {
      const row = this.tableData[index];
      const _r = {
        id: row.id,
        uNote: row.uNote,
      };
      obs.push(this.update(_r));
    });
    this.loading = true;
    forkJoin(obs).subscribe(resArr => {
      let allres = true;
      resArr.forEach(res => {
        if (res.msg === "Ok") {
          this.message.success('保存成功');
        } else {
          this.message.success('保存失败');
          allres = false;
        }
        if (allres) {
          this.query(false)
        }
      });
      this.needSaveIndexes.clear();
    })
  }

  /**
   * 修改
   */
  update(param) {
    const dataurl = environment.project + '/updownRoadm/update';
    return this.http.post(dataurl, param);
  }

}
